package com.myblog.web.admin;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.myblog.Mapper.typemapper;
import com.myblog.po.Type;
import org.springframework.beans.factory.annotation.Autowired;


import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/admin")
public class TypeController {


    @Autowired
   private typemapper tmap;

    @GetMapping("/types")
    public String types(@RequestParam(value = "page",required = false)Integer page, Model model)
    {
        if(page == null)
        {
            page = 1;
        }
        PageHelper.startPage(page,4);
        List<Type> types = tmap.listtype();
        PageInfo pageInfo = new PageInfo(types);
        model.addAttribute("page",pageInfo);

        return "admin/types";
    }


   /*跳转到编辑页*/
    @GetMapping("/types/input")
    public String input(Model model){

        model.addAttribute("type",new Type());

        return "admin/types-input";
    }

/*分类到编辑页  id查找分类信息*/
    @GetMapping("/types/{id}/input")
    public String editInput(@PathVariable Long id, Model model)
    {

        model.addAttribute("type",tmap.getType(id));
        return "/admin/types-input";

    }


/* 保存分类到传数据库文件*/
    @PostMapping("/typess")
    public String post(@RequestParam("id") Long id,@RequestParam("name") String name,Model model)
    {
            Type t1 = tmap.getTypeByName(name);

            if(t1!=null){
                model.addAttribute("messageerro","不可以重复");
                return "/admin/types-input";

            }
        if(name == null)
        {
            model.addAttribute("messageerro","名字不为空");
            return "/admin/types-input";
        }

        Type t = new Type();
        t.setName(name);
        t.setId(id);
          tmap.saveType(t);
           return "redirect:/admin/types";
    }

/*改动分类信息*/
    @PostMapping("/typess/{id}")
    public String editpost(@RequestParam("id") Long id,@RequestParam("name") String name,Model model)
    {
        Type t1 = tmap.getTypeByName(name);

        if(name == null)
        {
            model.addAttribute("messageerro","名字不为空");
            return "/admin/types-input";
        }

        Type t = new Type();
        t.setName(name);
        t.setId(id);
        tmap.updateType(t);
        return "redirect:/admin/types";
    }


    /*删除分类*/
    @GetMapping("/types/{id}/delete")
    public String delete(@PathVariable Long id)
    {
        tmap.deleteType(id);
        return "redirect:/admin/types";


    }



}


